/**
 * Copyright (c) 2005-2012 springside.org.cn
 */
package com.sheng.project.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

import java.lang.reflect.*;
import java.util.*;

/**
 * 反射工具类.
 * 提供调用 getter/setter 方法, 访问私有变量, 调用私有方法, 获取泛型类型 Class, 被 AOP 过的真实类等工具函数.
 *
 * @author calvin
 * @version 2013-01-15
 */
@SuppressWarnings("rawtypes")
@Slf4j
public class ReflectionKit {

    private static final String SETTER_PREFIX = "set";

    private static final String GETTER_PREFIX = "get";

    private static final String CGLIB_CLASS_SEPARATOR = "$$";

    /**
     * 调用 Getter 方法.
     * 支持多级，如：对象名.对象名.方法
     */
    public static Object invokeGetter(Object obj, String propertyName) {
        Object object = obj;
        for (String name : StringUtils.split(propertyName, ".")) {
            String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
            object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
        }
        return object;
    }

    /**
     * 调用 Setter 方法, 仅匹配方法名。
     * 支持多级，如：对象名.对象名.方法
     */
    public static void invokeSetter(Object obj, String propertyName, Object value) {
        Object object = obj;
        String[] names = StringUtils.split(propertyName, ".");
        for (int i = 0; i < names.length; i++) {
            if (i < names.length - 1) {
                String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
                object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
            } else {
                String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
                invokeMethodByName(object, setterMethodName, new Object[]{value});
            }
        }
    }

    /**
     * 直接读取对象属性值, 无视 private/protected 修饰符, 不经过 getter 函数.
     */
    public static Object getFieldValue(final Object obj, final String fieldName) {
        Field field = getAccessibleField(obj, fieldName);

        if (field == null) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
        }

        Object result = null;
        try {
            result = field.get(obj);
        } catch (IllegalAccessException e) {
            log.error("不可能抛出的异常{}", e.getMessage());
        }
        return result;
    }

    /**
     * 直接设置对象属性值, 无视 private/protected 修饰符, 不经过 setter 函数.
     */
    public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
        Field field = getAccessibleField(obj, fieldName);

        if (field == null) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
        }

        try {
            field.set(obj, value);
        } catch (IllegalAccessException e) {
            log.error("不可能抛出的异常:{}", e.getMessage());
        }
    }

    /**
     * 直接调用对象方法, 无视 private/protected 修饰符.
     * 用于一次性调用的情况，否则应使用 getAccessibleMethod() 函数获得 Method 后反复调用.
     * 同时匹配方法名+参数类型，
     */
    public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes, final Object[] args) {
        Method method = getAccessibleMethod(obj, methodName, parameterTypes);
        if (method == null) {
            throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
        }

        try {
            return method.invoke(obj, args);
        } catch (Exception e) {
            throw convertReflectionExceptionToUnchecked(e);
        }
    }

    /**
     * 直接调用对象方法, 无视 private/protected 修饰符，
     * 用于一次性调用的情况，否则应使用 getAccessibleMethodByName() 函数获得 Method 后反复调用.
     * 只匹配函数名，如果有多个同名函数调用第一个。
     */
    public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
        Method method = getAccessibleMethodByName(obj, methodName);
        if (method == null) {
            throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
        }

        try {
            return method.invoke(obj, args);
        } catch (Exception e) {
            throw convertReflectionExceptionToUnchecked(e);
        }
    }

    /**
     * 循环向上转型, 获取对象的 DeclaredField, 并强制设置为可访问.
     * <p>
     * 如向上转型到 Object 仍无法找到, 返回 null.
     */
    public static Field getAccessibleField(final Object obj, final String fieldName) {
        Validate.notNull(obj, "object can't be null");
        Validate.notBlank(fieldName, "fieldName can't be blank");
        for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                Field field = superClass.getDeclaredField(fieldName);
                makeAccessible(field);
                return field;
                // NO SONAR
            } catch (NoSuchFieldException e) {
                // Field 不在当前类定义,继续向上转型
                // new add
                continue;
            }
        }
        return null;
    }

    /**
     * 循环向上转型, 获取对象的 DeclaredField, 并强制设置为可访问.
     * <p>
     * 如向上转型到 Object 仍无法找到, 返回 null.
     */
    public static List<Field> getAccessibleFields(final Class<?> clazz) {
        Validate.notNull(clazz, "clazz can't be null");
        List<Field> fieldList = new ArrayList<>();
        for (Class<?> superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
            Field[] fields = superClass.getDeclaredFields();
            Collections.addAll(fieldList, fields);
        }
        return fieldList;
    }

    /**
     * 循环向上转型, 获取对象的 DeclaredField, 并强制设置为可访问.
     * <p>
     * 如向上转型到 Object 仍无法找到, 返回 null.
     */
    public static Field getAccessibleField(final Class<?> clazz, final String fieldName) {
        Validate.notNull(clazz, "clazz can't be null");
        Validate.notBlank(fieldName, "fieldName can't be blank");
        for (Class<?> superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                Field field = superClass.getDeclaredField(fieldName);
                makeAccessible(field);
                return field;
                // NO SONAR
            } catch (NoSuchFieldException e) {
                // Field 不在当前类定义,继续向上转型
                // new add
                continue;
            }
        }
        return null;
    }

    /**
     * 循环向上转型, 获取对象的 DeclaredMethod,并强制设置为可访问.
     * 如向上转型到 Object 仍无法找到, 返回 null.
     * 匹配函数名+参数类型。
     * <p>
     * 用于方法需要被多次调用的情况. 先使用本函数先取得 Method,然后调用 Method.invoke(Object obj, Object... args)
     */
    public static Method getAccessibleMethod(final Object obj, String methodName, final Class<?>... parameterTypes) {
        Validate.notNull(obj, "object can't be null");
        Validate.notBlank(methodName, "methodName can't be blank");

        for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
            try {
                Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
                makeAccessible(method);
                return method;
            } catch (NoSuchMethodException e) {
                // Method 不在当前类定义,继续向上转型
                // new add
                continue;
            }
        }
        return null;
    }

    /**
     * 循环向上转型, 获取对象的 DeclaredMethod,并强制设置为可访问.
     * 如向上转型到 Object 仍无法找到, 返回 null.
     * 匹配函数名+参数类型。
     * <p>
     * 用于方法需要被多次调用的情况. 先使用本函数先取得 Method,然后调用 Method.invoke(Object obj, Object... args)
     */
    public static Method getAccessibleMethod(final Class<?> clazz, final String methodName, final Class<?>... parameterTypes) {
        Validate.notNull(clazz, "clazz can't be null");
        Validate.notBlank(methodName, "methodName can't be blank");

        for (Class<?> searchType = clazz; searchType != Object.class; searchType = searchType.getSuperclass()) {
            try {
                Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
                makeAccessible(method);
                return method;
            } catch (NoSuchMethodException e) {
                // Method 不在当前类定义,继续向上转型
                // new add
                continue;
            }
        }
        return null;
    }

    /**
     * 循环向上转型, 获取对象的 DeclaredMethod,并强制设置为可访问.
     * 如向上转型到 Object 仍无法找到, 返回 null.
     * 只匹配函数名。
     * <p>
     * 用于方法需要被多次调用的情况. 先使用本函数先取得 Method,然后调用 Method.invoke(Object obj, Object... args)
     */
    public static Method getAccessibleMethodByName(final Object obj, final String methodName) {
        Validate.notNull(obj, "object can't be null");
        Validate.notBlank(methodName, "methodName can't be blank");

        for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
            Method[] methods = searchType.getDeclaredMethods();
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    makeAccessible(method);
                    return method;
                }
            }
        }
        return null;
    }

    /**
     * 改变 private/protected 的方法为 public，尽量不调用实际改动的语句，避免 JDK 的 SecurityManager 抱怨。
     */
    public static void makeAccessible(Method method) {
        if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
            method.setAccessible(true);
        }
    }

    /**
     * 改变 private/protected 的成员变量为 public，尽量不调用实际改动的语句，避免 JDK 的 SecurityManager 抱怨。
     */
    public static void makeAccessible(Field field) {
        if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
            field.setAccessible(true);
        }
    }

    /**
     * 通过反射, 获得 Class 定义中声明的泛型参数的类型, 注意泛型必须定义在父类处
     * 如无法找到, 返回 Object.class.
     * eg.
     * public UserDao extends HibernateDao<User>
     *
     * @param clazz The class to introspect
     * @return the first generic declaration, or Object.class if cannot be determined
     */
    @SuppressWarnings("unchecked")
    public static <T> Class<T> getClassGenericType(final Class clazz) {
        return getClassGenericType(clazz, 0);
    }

    /**
     * 通过反射, 获得 Class 定义中声明的父类的泛型参数的类型.
     * 如无法找到, 返回 Object.class.
     * <p>
     * 如public UserDao extends HibernateDao<User,Long>
     *
     * @param clazz clazz The class to introspect
     * @param index the Index of the generic declaration,start from 0.
     * @return the index generic declaration, or Object.class if cannot be determined
     */
    public static Class getClassGenericType(final Class clazz, final int index) {

        Type genType = clazz.getGenericSuperclass();

        if (!(genType instanceof ParameterizedType)) {
            log.warn("{}'s superclass not ParameterizedType", clazz.getSimpleName());
            return Object.class;
        }

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0) {
            log.warn("Index: {}, Size of {}'s Parameterized Type: {}", index, clazz.getSimpleName(), params.length);
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            log.warn("{} not set the actual class on superclass generic parameter", clazz.getSimpleName());
            return Object.class;
        }

        return (Class) params[index];
    }

    /**
     * 将反射时的 checked exception 转换为 unchecked exception.
     */
    public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
        if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException || e instanceof NoSuchMethodException) {
            return new IllegalArgumentException(e);
        } else if (e instanceof InvocationTargetException) {
            return new RuntimeException(((InvocationTargetException) e).getTargetException());
        } else if (e instanceof RuntimeException) {
            return (RuntimeException) e;
        }
        return new RuntimeException("Unexpected Checked Exception.", e);
    }

    public static String[] getNullProperties(Object object) {
        Field[] declaredFields = object.getClass().getDeclaredFields();
        List<String> nullProperties = new ArrayList<>();
        try {
            for (Field declaredField : declaredFields) {
                // 设置可以对 private 属性的对象进行访问
                declaredField.setAccessible(true);
                if (declaredField.get(object) == null) {
                    // 将为空的属性添加到 list 中
                    nullProperties.add(declaredField.getName());
                }
            }
        } catch (IllegalAccessException e) {
            log.error("IllegalAccessException 发生异常：", e);
            return null;
        }
        // nullProperties.stream().toArray(String[]::new);
        return nullProperties.toArray(new String[0]);
    }

    /**
     * 实体类转 Map
     */
    public static Map<String, Object> entityToMap(Object object) {
        Map<String, Object> map = new HashMap<>();
        for (Field field : object.getClass().getDeclaredFields()) {
            try {
                boolean flag = field.isAccessible();
                field.setAccessible(true);
                Object o = field.get(object);
                map.put(field.getName(), o);
                field.setAccessible(flag);
            } catch (Exception e) {
                log.error("发生异常：", e);
            }
        }
        return map;
    }

    /**
     * Map 转实体类
     *
     * @param map    需要初始化的数据，key 字段必须与实体类的成员名字一样，否则赋值为空
     * @param entity 需要转化成的实体类
     * @param <T>    泛型
     * @return 实体类
     */
    public static <T> T mapToEntity(Map<String, Object> map, Class<T> entity) {
        T t = null;
        try {
            t = entity.newInstance();
            for (Field field : entity.getDeclaredFields()) {
                if (map.containsKey(field.getName())) {
                    boolean flag = field.isAccessible();
                    field.setAccessible(true);
                    Object object = map.get(field.getName());
                    if (object != null && field.getType().isAssignableFrom(object.getClass())) {
                        field.set(t, object);
                    }
                    field.setAccessible(flag);
                }
            }
            return t;
        } catch (InstantiationException e) {
            log.error("InstantiationException 发生异常：", e);
        } catch (IllegalAccessException e) {
            log.error("IllegalAccessException 发生异常：", e);
        }
        return t;
    }
}
